import 'package:byw_blog/network/NetworkInterface.dart';
import 'package:byw_blog/pages/HomePage.dart';
import 'package:byw_blog/pages/ViewRssPage.dart';
import 'package:byw_blog/widget/ArticleListWidget.dart';
import 'package:flutter/material.dart';

class RealTimeInfoPage extends StatefulWidget {
  const RealTimeInfoPage({Key? key}) : super(key: key);

  @override
  State<RealTimeInfoPage> createState() => _RealTimeInfoPageState();
}

class _RealTimeInfoPageState extends State<RealTimeInfoPage> {
  List<dynamic> allArticles = [];

  @override
  void initState() {
    super.initState();
    List<dynamic> articles = [];
    NetworkInterface.getTimeline().then((value) {
      value.forEach((key, value) {
        articles.addAll(value);
      });
      setState(() {
        allArticles.addAll(articles);
        articles.clear();
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("发现"),
        ),
        body: Container(
          width: double.infinity,
          height: double.infinity,
          child: SingleChildScrollView(
              child: Column(
            children: List.generate(
                allArticles.length,
                (index) => InkWell(
                    onTap: () => clickArticle(allArticles[index]['title']),
                    child: ArticleListWidget(
                        allArticles[index]['title'],
                        allArticles[index]['author'] ?? "",
                        allArticles[index]['category']))),
          )),
        ));
  }

  clickArticle(String title) {
    HomePage.rss?.forEach((element) {
      if (element.title == title) {
        int start = element.author!.lastIndexOf('(') + 1;
        int end = element.author!.lastIndexOf(')');
        var author = element.author?.substring(start, end);
        final feedItems = {
          'title': element.title,
          // 'content':item.content!.value,
          'creator': element.dc!.creator,
          // 'image':item.media!.contents![0].url,
          'link': element.link,
          'pubDate': element.pubDate,
          'author': author,
          'content': element.content!.value
        };
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => ViewRssPage(RssFeed: feedItems)));

        return;
      }
    });
  }
}
